<template>
  <!-- <LoginFormTitle v-show="getShow" class="enter-x" /> -->
  <div class="logo-style">
    <img src="../../../assets/images/ALPlogo.png" />
  </div>
  <Tabs v-model:activeKey="activeKey">
    <TabPane key="1" tab="帐号密码登录" :style="{ color: 'green' }">
      <Form
        class="p-4 enter-x"
        :model="formData"
        :rules="getFormRules"
        ref="formRef"
        v-show="getShow"
        @keypress.enter="handleLogin"
      >
        <FormItem name="account" class="enter-x">
          <Input
            size="large"
            v-model:value="formData.account"
            :placeholder="t('sys.login.userName')"
            class="fix-auto-fill"
          />
        </FormItem>
        <FormItem name="password" class="enter-x">
          <InputPassword
            size="large"
            visibilityToggle
            v-model:value="formData.password"
            :placeholder="t('sys.login.password')"
          />
        </FormItem>

        <ARow class="enter-x">
          <ACol :span="12">
            <FormItem>
              <!-- No logic, you need to deal with it yourself -->
              <Checkbox v-model:checked="rememberMe" size="small">
                <span style="margin-left: 5px; color: #ffffff; font-size: 14px">
                  {{ t('sys.login.rememberMe') }}
                </span>
              </Checkbox>
            </FormItem>
          </ACol>
          <!-- <ACol :span="12">
        <FormItem :style="{ 'text-align': 'right' }">
          <Button type="link" size="small" @click="setLoginState(LoginStateEnum.RESET_PASSWORD)">
            {{ t('sys.login.forgetPassword') }}
          </Button>
        </FormItem>
      </ACol> -->
        </ARow>

        <FormItem class="enter-x">
          <Button
            class="submit-button"
            type="primary"
            size="large"
            block
            @click="handleLogin"
            :loading="loading"
          >
            {{ t('sys.login.loginButton') }}
          </Button>
          <!-- <Button size="large" class="mt-4 enter-x" block @click="handleRegister">
        {{ t('sys.login.registerButton') }}
      </Button> -->
        </FormItem>
        <div style="margin-top: 12px; text-align: right">
          <span style="color: #bebebe; font-size: 14px">Copyright © 2024 AInnovation ALP</span>
        </div>
      </Form>
    </TabPane>
  </Tabs>
</template>
<script lang="ts" setup>
  import { reactive, ref, unref, computed, onMounted } from 'vue';

  import { Checkbox, Form, Input, Row, Col, Button, Tabs, TabPane } from 'ant-design-vue';

  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';

  import { useUserStore } from '/@/store/modules/user';
  import { LoginStateEnum, useLoginState, useFormRules, useFormValid } from './useLogin';
  import { useDesign } from '/@/hooks/web/useDesign';
  import { Base64 } from 'js-base64';


  //import { onKeyStroke } from '@vueuse/core';

  const ACol = Col;
  const ARow = Row;
  const FormItem = Form.Item;
  const InputPassword = Input.Password;
  const { t } = useI18n();
  const { notification, createErrorModal } = useMessage();
  const { prefixCls } = useDesign('login');
  const userStore = useUserStore();
  const activeKey = ref('1');
  const { getLoginState } = useLoginState();
  const { getFormRules } = useFormRules();

  const formRef = ref();
  const loading = ref(false);
  const rememberMe = ref(false);

  const formData = reactive({
    account: '',
    password: '',
  });

  const { validForm } = useFormValid(formRef);

  //onKeyStroke('Enter', handleLogin);

  const getShow = computed(() => unref(getLoginState) === LoginStateEnum.LOGIN);
  onMounted(async () => {
    // 在页面加载时从cookie获取登录信息
    let account = getCookie('account');
    let password = Base64.decode(getCookie('password'));
    console.log(`output->password`, password);
    // 如果存在赋值给表单，并且将记住密码勾选
    if (account) {
      formData.account = account;
      formData.password = password;
      rememberMe.value = true;
    }
  });
  async function handleLogin() {
    const data = await validForm();
    if (!data) return;
    try {
      loading.value = true;
      const userInfo = await userStore.login([data.account, data.password]) as any;
      if (userInfo) {
        setUserInfo(data);
        notification.success({
          message: t('sys.login.loginSuccessTitle'),
          description: `${t('sys.login.loginSuccessDesc')}: ${userInfo.realName}`,
          duration: 3,
        });
      }
    } catch (error) {
      createErrorModal({
        title: t('sys.api.errorTip'),
        content: (error as unknown as Error).message || t('sys.api.networkExceptionMsg'),
        getContainer: () => document.body.querySelector(`.${prefixCls}`) || document.body,
      });
    } finally {
      loading.value = false;
    }
  }
  // 储存表单信息
  function setUserInfo(data) {
    // 判断用户是否勾选记住密码，如果勾选，向cookie中储存登录信息，
    // 如果没有勾选，储存的信息为空
    if (rememberMe.value) {
      setCookie('account', data.account, 86400000);
      // base64加密密码
      let password = Base64.encode(data.password);
      setCookie('password', password, 86400000);
    } else {
      setCookie('account', '', null);
      setCookie('password', '', null);
    }
   
  }
  // 获取cookie
  function getCookie(key) {
    if (document.cookie.length > 0) {
      let start = document.cookie.indexOf(key + '=');
      if (start !== -1) {
        start = start + key.length + 1;
        let end = document.cookie.indexOf(';', start);
        if (end === -1) end = document.cookie.length;
        return unescape(document.cookie.substring(start, end));
      }
    }
    return '';
  }
  // 保存cookie
  function setCookie(cName, value, expiredays) {
    let exdate = new Date();
    exdate.setDate(exdate.getDate() + expiredays);
    document.cookie =
      cName +
      '=' +
      decodeURIComponent(value) +
      (expiredays == null ? '' : ';expires=' + exdate.toUTCString());
  }
</script>
<style lang="less" scoped>
  .logo-style {
    flex: 1;
    width: 219px;
    margin-left: 122px;
  }

  :deep(.ant-tabs-tab.ant-tabs-tab-active .ant-tabs-tab-btn) {
    color: #ff792b !important;
    text-shadow: 0 0 0.25px currentcolor;
  }

  :deep(.ant-tabs-ink-bar) {
    position: absolute;
    background: #ff792b !important;
    pointer-events: none;
  }

  .submit-button {
    width: 100%;
    letter-spacing: 2px;
    background-color: #ff792b; /* 自定义颜色 */
    color: white; /* 文本颜色 */
  }
</style>
